<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/22
 * Time: 下午5:12
 */

namespace App\Http\Services;

use Illuminate\Support\Facades\Redis;
use App\Exceptions\ErrorCodeException;
use App\Http\Model\ContentCheck;
use App\Http\Model\FinanceRoomWallet;
use App\Http\Model\Gift;
use App\Http\Model\Guard;
use App\Http\Model\Mall;
use App\Http\Model\Medal;
use App\Http\Model\Room;
use App\Http\Model\RoomBackgroundPicture\BackgroundPictureManagement;
use App\Http\Model\RoomHostMicro;
use App\Http\Model\RoomMicro;
use App\Http\Model\RoomHeart;
use App\Http\Model\RoomMelee;
use App\Http\Model\RoomTally;
use App\Http\Model\RoomUser;
use App\Http\Model\System;
use App\Http\Model\SystemConfig;
use App\Http\Model\Union;
use App\Http\Model\UnionUser;
use App\Http\Model\User;
use App\Http\Model\Hint;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\UserProp;
use App\Http\Model\RoomHot;
use App\Http\Model\UserVerify;
use App\Lib\rc;
use App\Http\Model\RoomTurntable;
use Illuminate\Support\Facades\Log;
use App\Http\Services\UserFilterServices;
use App\Http\Services\ZegoServices;
use App\Http\Services\NameplateServices;

class RoomUserServices extends CommonServices
{
    protected $model_room_user;
    protected $model_user;
    protected $model_room;
    protected $model_userwallet;
    protected $model_mall;
    protected $model_finance_room_wallet;
    protected $modelUserVerify;
    protected $modelMedal;
    protected $modelRoomMelee;
    protected $modelRoomTally;
    protected $modelRoomHeart;
    protected $modelRoomTurntable;
    protected $modelUnion;
    protected $modelUnionUser;
    protected $userPropModel;
    protected $contentCheckModel;
    protected $modelGift;
    protected $modelSystem;
    protected $modelRoomHostMicro;
    protected $modelGuard;
    protected $roomHotModel;
    protected $zegoServices;
    protected $nameplateService;

    //拍拍房记录缓存
    protected $roomPaiPaiKey = 'ROOMPAIPAI:LOG:';//hash ROOMPAIPAI:LOG:{roomId} => {string}=>{string}

    public function __construct()
    {
        $this->model_room_user = new RoomUser();
        $this->model_user = new User();
        $this->model_room = new Room();
        $this->model_userwallet = new FinanceUserWallet();
        $this->model_mall = new Mall();
        $this->model_finance_room_wallet = new FinanceRoomWallet();
        $this->modelUserVerify = new UserVerify();
        $this->modelMedal = new Medal();
        $this->modelRoomMelee = new RoomMelee();
        $this->modelRoomTally = new RoomTally();
        $this->modelRoomHeart = new RoomHeart();
        $this->modelRoomTurntable = new RoomTurntable();
        $this->modelUnion = new Union();
        $this->modelUnionUser = new UnionUser();
        $this->userPropModel = new UserProp();
        $this->contentCheckModel = new ContentCheck();
        $this->modelGift = new Gift();
        $this->modelSystem = new System();
        $this->modelRoomHostMicro = new RoomHostMicro();
        $this->modelGuard = new Guard();
        $this->roomHotModel = new RoomHot();
        $this->zegoServices = new ZegoServices();
        $this->nameplateService = new NameplateServices();

    }

    /**
     * 进入房间
     * @param $room_id
     * @return int|null
     */
    public function add($room_id, $password = null, $userAgent = '')
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return null;
        }
        $room_item = $this->model_room->get_room($room_id);

        //过滤 add by zxiaofee
        $userFilterServices = new UserFilterServices();
        $filter_room_ids = $userFilterServices->getRoomFilterResult($current_user['user_id']);
        if ($current_user['user_id'] != $room_item['user_id'] && in_array($room_id, $filter_room_ids)) {
            return Hint::ROOM_NOT_OPEN;
        }

        //cbd房间并且整顿中
        if ($room_item['business_type'] == 1 && $room_item['certified'] == 2) {
            return Hint::ROOM_RECTIFY;
        }

        //审核开关开启情况下，如果用户财富值小于400 不让进娱乐房
        $examine_switch = $this->modelSystem->getExamineSwitch('switch');
        if ($examine_switch == 1 && $room_item['room_type']['id'] == 4) {
            $user_wealth = $this->model_userwallet->get_wallet($current_user['user_id']);
            if ($user_wealth['wealth_balance'] < 400) {
                return Hint::ROOM_JOIN_ERROR;
            }
        }

        //最多金房间黑名单禁止进入
        $maximumGoldRoomIds = (new MaximumGoldRoomServices())->getRoomIds();

        //检查最多金黑名单
        if ($maximumGoldRoomIds && in_array($room_id, $maximumGoldRoomIds)) {
            //读取最多金限制配置
            $roomBlacklist = (new SystemConfig())->getRoomBlockConfig();
            $maximumGoldBlackUserUids = $roomBlacklist['maximum_gold_block_user'] ?? [];
            $maximumGoldBlackCityList = $roomBlacklist['maximum_gold_block_city'] ?? [];

            //这些用户不能显示最多金房间
            if (!empty($maximumGoldBlackUserUids)) {
                if (in_array($current_user['user_uid'], $maximumGoldBlackUserUids)) {
                    return Hint::ROOM_JOIN_ERROR2;
                }
            }
            //这些城市不能显示最多金房间
            if (!empty($maximumGoldBlackCityList)) {
                $userCity = getCityByIp();// 获取用户城市
                if (in_array($userCity, $maximumGoldBlackCityList)) {
                    return Hint::ROOM_JOIN_ERROR2;
                }
            }
        }

        if (empty($room_item)) {
            return Hint::ROOM_NO_EXIST; //房间不存在
        }

        $user_id = $current_user['user_id'];
        $parse_app_UA = $this->parse_app_UA();

        $close_timestamp = $this->model_room->get_close_timestamp($room_id);
        $opened = $this->model_room->get_opened($room_id);
        $room_item['opened'] = $opened;
        $room_item['allow_open'] = null;
        //审核时显示特定公告
        $examine_switch = $this->modelSystem->getExamineSwitch('switch');
        if ($examine_switch == 1) {
            $room_item['notice'] = $this->modelSystem->getExamineSwitch('notice');
        }
        $role = null;
        if (!$opened) {
            $room_item['allow_open'] = false;
            $this->model_room->setAig($room_id);
            $role = $this->model_room->get_role($room_id, $current_user['user_id']);
            if ($role == 0) {
                return Hint::ROOM_NOT_OPEN;
            } else {
                $room_item['allow_open'] = true;
            }
        }


        if ($this->model_room->get_shotoff($room_id, $user_id)) {
            return Hint::ROOM_USER_SHOT_OFF;
        }


        if ($role === null) {
            $role = $this->model_room->get_role($room_id, $current_user['user_id']);
        }

        $pwd = 0;
        $user_super = $this->model_user->is_super($user_id);
        $room_password = $this->model_room->get_password($room_id);
        if ($room_password !== null && $role < 2) {
            if ($password === null) {
                // 房间需要密码
                return Hint::ROOM_PASSWORD_NEED;
            }
            if ($room_password !== $password) {
                if (!$user_super) {
                    // 密码错误
                    return Hint::ROOM_PASSWORD_ERR;
                }
            }
        }
        if ($room_password !== null) {
            $pwd = 1;
        }

        $host_user = $this->model_user->get_user($room_item['user_id']);
        $wallet = $this->model_userwallet->get_wallet($room_item['user_id']);
        $host_user['charm_balance'] = $wallet['charm_balance'];
        $room_item['host'] = $host_user;
        $room_item['hot'] = $this->roomHotModel->get($room_id);
        $room_item['wealth_value'] = $this->model_finance_room_wallet->get_wallet($room_id);

        $users_count = $this->model_room_user->get_users_count($room_id);
        $room_item['online_count'] = $users_count;
        $room_item['is_block'] = $this->model_room->get_block($room_id, $user_id);
        $room_item['is_collect'] = $this->model_room->get_collect($room_id, $user_id);
        $room_item['user_role'] = $role;
        $room_item['close_timestamp'] = $close_timestamp;
        $room_item['free_micro'] = $this->model_room->get_freemicro($room_id);
        $room_item['screen_opened'] = $this->model_room->get_screen_opened($room_id);
        $room_item['volume_closed'] = $this->model_room->get_volume_closed($room_id);
        $room_item['password'] = $pwd;
        $room_item['chat_room_id'] = intval(config('rong_cloud.room_id_offset')) + intval($room_item['room_id']);
        // $agora = new agora();
        // if ($this->model_room->getAig($room_id)) {
        //     $agora->aig();
        // }
        $room_item['agora_token'] = '';//$agora->getToken($room_id, $user_id);//声网token
        $room_item['zego_token'] = $this->zegoServices->getZegoToken($room_id, $user_id);//即构token
        $room_item['mode_type'] = $this->model_room->getModeType($room_id);

        $room_item['chat_mode_switch'] = 0; //声网测试
        $room_item['good_audio_mode_switch'] = 0; //声网测试
        $room_item['great_audio_mode_switch'] = 0; //声网测试
        $room_item['game_audio_mode_switch'] = 0; //声网测试
        $room_item['topic'] = $this->model_room->getTopic($room_id);

        $room_item['room_image_examine_status'] = 1;// 房间封面图片审核状态 0=待审核 1=已审核
        $room_item['room_image_examine'] = '';// 房间封面图片审核状态 0=待审核 则存在审核图片地址，否则为空值
        $room_item['room_tag_list'] = [];// 房间标签列表
        // 查询房间封面是否存在未审核数据
        $getRoomImageExamine = $this->model_room->getRoomImageExamine(['room_id' => $room_id, 'type' => 0, 'status' => 0]);
        if (!empty($getRoomImageExamine)) {
            $room_item['room_image_examine_status'] = 0;
            $room_item['room_image_examine'] = build_image($getRoomImageExamine['image']);
        }
        // 当前房间分类下的标签列表
        $room_item['room_tag_list'] = $this->model_room->getRoomTagListByRoomType($room_item['room_type']['id'] ?? 0);
        foreach ($room_item['room_tag_list'] as $key => $value) {
            // 是否设置当前标签 0=未设置 1=已设置
            $room_item['room_tag_list'][$key]['is_used'] = 0;
            if (!empty($room_item['room_tag_id'] ?? 0) and $room_item['room_tag_id'] == $value['tag_id']) {
                $room_item['room_tag_list'][$key]['is_used'] = 1;
            }
        }
        $room_item['melee_opened'] = $this->modelRoomMelee->getState($room_id);
        $room_item['tally_opened'] = $this->modelRoomTally->opened($room_id);
        $room_item['heart_opened'] = $this->modelRoomHeart->getState($room_id);
        if ($room_item['heart_opened'] > 0) {
            $room_item['heart_opened'] = 1;
        }


        $room_item['turntable_opened'] = $this->modelRoomTurntable->getTurntableOpened($room_id); //房间转盘是否开启
        $room_item['pk_opened'] = 0; //获取是否开启PK

        //获取房间公会信息
        $union_room = $this->modelUnion->checkUnionRoom($room_id);
        $room_item['has_union'] = 0; //是否有公会
        $room_item['union_id'] = 0; //公会ID
        if ($union_room) {
            $room_item['has_union'] = 1;
            $room_item['union_id'] = $union_room['un_id'];
        }

        $this->userPropModel->resetPropInvalid($user_id, 15); //重置道具临时失效逻辑
        $propUseInfo = $this->userPropModel->getPropUseTime($user_id, 15); // 获取用户是否使用道具
        $room_item['user_prop']['hide_info'] = $propUseInfo ? true : false;


        $room_item['placard'] = true;
        $room_item['dice'] = true;

        //获取房间热度召集令信息
        $room_item['hot_call'] = ['status' => 0, 'time' => 0];

        // 统计用户进入房间
        if ($current_user['novice'] == 1) {
            $this->model_room->setJoinNewUserId($room_id, $user_id);
        }
        $this->model_room->setJoinUserId($room_id, $user_id);

        // 获取神豪开关状态
        $room_item['god_hao_switch'] = $this->model_room->getGodHaoSwitch($room_id);

        // 房间公平是否展示礼物消息 默认展示
        $switch_key = 'gift_show_switch';
        $res = (new RoomServices())->getRoomSwitchCommon($room_id, $switch_key);
        $room_item[$switch_key] = $res;

        if (!empty($room_item['background_pic'])) {
            $exceed = BackgroundPictureManagement::checkPictureExpire($room_item['background_pic']);
            if ($exceed == false) {
                $room_item['background_pic'] = "";
            }
        }

        //房间的管理员信息
        $admins = $this->model_room->get_roles_limit($room_id, 0, 100);
        foreach ($admins as &$a) {
            if ($a['role_type'] == 2) { //房主
                $a['is_super'] = $a['user_id'] == $room_item['user_id'] ? 0 : 1; //检查超管
            } else {
                $a['is_super'] = 0;
            }
        }
        $room_item['admin_list'] = $admins;

        $code = '';
        if ($current_user['is_open_code'] == 1 && $current_user['code']) {
            $code = $current_user['code'];
        }


        //APP分享链接
        if (checkAppEnv()) {
            $share_url = 'http://123.56.126.158:7080/activity/share/index.html';
        } else {
            $share_url = 'http://ccoss.yinlaiwlkj.top/activity/share/index.html';
        }

        $share_url = sprintf('%s?room_id=%s&invite_code=%s', $share_url, $room_id, $code);

        $room_item['share_url'] = $share_url;
        //真爱榜是否显示
        $roomLoveOpenStatus = $this->model_room->get_love_rank_status($room_id);
        $room_item['love_rank_status'] = $roomLoveOpenStatus;

        //拍拍房
        if ($room_item['type_id'] == 46) {
            //状态 0=未开始 1=进行中 2=确定选择 3=派发选择
            $room_item['paipai_info'] = ['status' => 0, 'score_12' => 0, 'score_34' => 0, 'score_56' => 0, 'end_time' => 0, 'paipai_url' => build_url('/rank/paipai/info.png')];
            //拍拍房
            $cacheKey = $this->roomPaiPaiKey . $room_id;
            $info = Redis::HGETALL($cacheKey);
            if (!empty($info)) {
                $room_item['paipai_info']['status'] = $info['status'];
                $room_item['paipai_info']['score_12'] = $info['score_12'];
                $room_item['paipai_info']['score_34'] = $info['score_34'];
                $room_item['paipai_info']['score_56'] = $info['score_56'];
                $room_item['paipai_info']['end_time'] = strtotime($info['created_at']) + $info['second_num'];
            }
        }

        return $room_item;
    }

    /**
     * 进入房间不需要密码
     * @param $room_id
     * @return int|null
     */
    public function addNoPwd($room_id, $userAgent = '')
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return null;
        }
        $room_item = $this->model_room->get_room($room_id);

        //过滤 add by zxiaofee
        $userFilterServices = new UserFilterServices();
        $filter_room_ids = $userFilterServices->getRoomFilterResult($current_user['user_id']);
        if ($current_user['user_id'] != $room_item['user_id'] && in_array($room_id, $filter_room_ids)) {
            return Hint::ROOM_NOT_OPEN;
        }

        //cbd房间并且整顿中
        if ($room_item['business_type'] == 1 && $room_item['certified'] == 2) {
            return Hint::ROOM_RECTIFY;
        }

        //审核开关开启情况下，如果用户财富值小于400 不让进娱乐房
        $examine_switch = $this->modelSystem->getExamineSwitch('switch');
        if ($examine_switch == 1 && $room_item['room_type']['id'] == 4) {
            $user_wealth = $this->model_userwallet->get_wallet($current_user['user_id']);
            if ($user_wealth['wealth_balance'] < 400) {
                return Hint::ROOM_JOIN_ERROR;
            }
        }

        //最多金房间黑名单禁止进入
        $maximumGoldRoomIds = (new MaximumGoldRoomServices())->getRoomIds();

        //检查最多金黑名单
        if ($maximumGoldRoomIds && in_array($room_id, $maximumGoldRoomIds)) {
            //读取最多金限制配置
            $roomBlacklist = (new SystemConfig())->getRoomBlockConfig();
            $maximumGoldBlackUserUids = $roomBlacklist['maximum_gold_block_user'] ?? [];
            $maximumGoldBlackCityList = $roomBlacklist['maximum_gold_block_city'] ?? [];

            //这些用户不能显示最多金房间
            if (!empty($maximumGoldBlackUserUids)) {
                if (in_array($current_user['user_uid'], $maximumGoldBlackUserUids)) {
                    return Hint::ROOM_JOIN_ERROR2;
                }
            }
            //这些城市不能显示最多金房间
            if (!empty($maximumGoldBlackCityList)) {
                $userCity = getCityByIp();// 获取用户城市
                if (in_array($userCity, $maximumGoldBlackCityList)) {
                    return Hint::ROOM_JOIN_ERROR2;
                }
            }
        }

        if (empty($room_item)) {
            return Hint::ROOM_NO_EXIST; //房间不存在
        }

        $user_id = $current_user['user_id'];
        $parse_app_UA = $this->parse_app_UA();

        $close_timestamp = $this->model_room->get_close_timestamp($room_id);
        $opened = $this->model_room->get_opened($room_id);
        $room_item['opened'] = $opened;
        $room_item['allow_open'] = null;
        //审核时显示特定公告
        $examine_switch = $this->modelSystem->getExamineSwitch('switch');
        if ($examine_switch == 1) {
            $room_item['notice'] = $this->modelSystem->getExamineSwitch('notice');
        }
        $role = null;
        if (!$opened) {
            $room_item['allow_open'] = false;
            $this->model_room->setAig($room_id);
            $role = $this->model_room->get_role($room_id, $current_user['user_id']);
            if ($role == 0) {
                return Hint::ROOM_NOT_OPEN;
            } else {
                $room_item['allow_open'] = true;
            }
        }


        if ($this->model_room->get_shotoff($room_id, $user_id)) {
            return Hint::ROOM_USER_SHOT_OFF;
        }


        if ($role === null) {
            $role = $this->model_room->get_role($room_id, $current_user['user_id']);
        }

        $pwd = 0;
        $room_password = $this->model_room->get_password($room_id);
        if ($room_password !== null) {
            $pwd = 1;
        }

        $host_user = $this->model_user->get_user($room_item['user_id']);
        $wallet = $this->model_userwallet->get_wallet($room_item['user_id']);
        $host_user['charm_balance'] = $wallet['charm_balance'];
        $room_item['host'] = $host_user;
        $room_item['hot'] = $this->roomHotModel->get($room_id);
        $room_item['wealth_value'] = $this->model_finance_room_wallet->get_wallet($room_id);

        $users_count = $this->model_room_user->get_users_count($room_id);
        $room_item['online_count'] = $users_count;
        $room_item['is_block'] = $this->model_room->get_block($room_id, $user_id);
        $room_item['is_collect'] = $this->model_room->get_collect($room_id, $user_id);
        $room_item['user_role'] = $role;
        $room_item['close_timestamp'] = $close_timestamp;
        $room_item['free_micro'] = $this->model_room->get_freemicro($room_id);
        $room_item['screen_opened'] = $this->model_room->get_screen_opened($room_id);
        $room_item['volume_closed'] = $this->model_room->get_volume_closed($room_id);
        $room_item['password'] = $pwd;
        $room_item['chat_room_id'] = intval(config('rong_cloud.room_id_offset')) + intval($room_item['room_id']);
        // $agora = new agora();
        // if ($this->model_room->getAig($room_id)) {
        //     $agora->aig();
        // }
        $room_item['agora_token'] = '';//$agora->getToken($room_id, $user_id);//声网token
        $room_item['zego_token'] = $this->zegoServices->getZegoToken($room_id, $user_id);//即构token
        $room_item['mode_type'] = $this->model_room->getModeType($room_id);

        $room_item['chat_mode_switch'] = 0; //声网测试
        $room_item['good_audio_mode_switch'] = 0; //声网测试
        $room_item['great_audio_mode_switch'] = 0; //声网测试
        $room_item['game_audio_mode_switch'] = 0; //声网测试
        $room_item['topic'] = $this->model_room->getTopic($room_id);

        $room_item['room_image_examine_status'] = 1;// 房间封面图片审核状态 0=待审核 1=已审核
        $room_item['room_image_examine'] = '';// 房间封面图片审核状态 0=待审核 则存在审核图片地址，否则为空值
        $room_item['room_tag_list'] = [];// 房间标签列表
        // 查询房间封面是否存在未审核数据
        $getRoomImageExamine = $this->model_room->getRoomImageExamine(['room_id' => $room_id, 'type' => 0, 'status' => 0]);
        if (!empty($getRoomImageExamine)) {
            $room_item['room_image_examine_status'] = 0;
            $room_item['room_image_examine'] = build_image($getRoomImageExamine['image']);
        }
        // 当前房间分类下的标签列表
        $room_item['room_tag_list'] = $this->model_room->getRoomTagListByRoomType($room_item['room_type']['id'] ?? 0);
        foreach ($room_item['room_tag_list'] as $key => $value) {
            // 是否设置当前标签 0=未设置 1=已设置
            $room_item['room_tag_list'][$key]['is_used'] = 0;
            if (!empty($room_item['room_tag_id'] ?? 0) and $room_item['room_tag_id'] == $value['tag_id']) {
                $room_item['room_tag_list'][$key]['is_used'] = 1;
            }
        }
        $room_item['melee_opened'] = $this->modelRoomMelee->getState($room_id);
        $room_item['tally_opened'] = $this->modelRoomTally->opened($room_id);
        $room_item['heart_opened'] = $this->modelRoomHeart->getState($room_id);
        if ($room_item['heart_opened'] > 0) {
            $room_item['heart_opened'] = 1;
        }


        $room_item['turntable_opened'] = $this->modelRoomTurntable->getTurntableOpened($room_id); //房间转盘是否开启
        $room_item['pk_opened'] = 0; //获取是否开启PK

        //获取房间公会信息
        $union_room = $this->modelUnion->checkUnionRoom($room_id);
        $room_item['has_union'] = 0; //是否有公会
        $room_item['union_id'] = 0; //公会ID
        if ($union_room) {
            $room_item['has_union'] = 1;
            $room_item['union_id'] = $union_room['un_id'];
        }

        $this->userPropModel->resetPropInvalid($user_id, 15); //重置道具临时失效逻辑
        $propUseInfo = $this->userPropModel->getPropUseTime($user_id, 15); // 获取用户是否使用道具
        $room_item['user_prop']['hide_info'] = $propUseInfo ? true : false;


        $room_item['placard'] = true;
        $room_item['dice'] = true;

        //获取房间热度召集令信息
        $room_item['hot_call'] = ['status' => 0, 'time' => 0];

        // 统计用户进入房间
        if ($current_user['novice'] == 1) {
            $this->model_room->setJoinNewUserId($room_id, $user_id);
        }
        $this->model_room->setJoinUserId($room_id, $user_id);

        // 获取神豪开关状态
        $room_item['god_hao_switch'] = $this->model_room->getGodHaoSwitch($room_id);

        // 房间公平是否展示礼物消息 默认展示
        $switch_key = 'gift_show_switch';
        $res = (new RoomServices())->getRoomSwitchCommon($room_id, $switch_key);
        $room_item[$switch_key] = $res;

        if (!empty($room_item['background_pic'])) {
            $exceed = BackgroundPictureManagement::checkPictureExpire($room_item['background_pic']);
            if ($exceed == false) {
                $room_item['background_pic'] = "";
            }
        }

        //房间的管理员信息
        $admins = $this->model_room->get_roles_limit($room_id, 0, 100);
        foreach ($admins as &$a) {
            if ($a['role_type'] == 2) { //房主
                $a['is_super'] = $a['user_id'] == $room_item['user_id'] ? 0 : 1; //检查超管
            } else {
                $a['is_super'] = 0;
            }
        }
        $room_item['admin_list'] = $admins;

        $code = '';
        if ($current_user['is_open_code'] == 1 && $current_user['code']) {
            $code = $current_user['code'];
        }


        //APP分享链接
        if (checkAppEnv()) {
            $share_url = 'http://123.56.126.158:7080/activity/share/index.html';
        } else {
            $share_url = 'http://ccoss.yinlaiwlkj.top/activity/share/index.html';
        }

        $share_url = sprintf('%s?room_id=%s&invite_code=%s', $share_url, $room_id, $code);

        $room_item['share_url'] = $share_url;
        //真爱榜是否显示
        $roomLoveOpenStatus = $this->model_room->get_love_rank_status($room_id);
        $room_item['love_rank_status'] = $roomLoveOpenStatus;

        //拍拍房
        if ($room_item['type_id'] == 46) {
            //状态 0=未开始 1=进行中 2=确定选择 3=派发选择
            $room_item['paipai_info'] = ['status' => 0, 'score_12' => 0, 'score_34' => 0, 'score_56' => 0, 'end_time' => 0, 'paipai_url' => build_url('/rank/paipai/info.png')];
            //拍拍房
            $cacheKey = $this->roomPaiPaiKey . $room_id;
            $info = Redis::HGETALL($cacheKey);
            if (!empty($info)) {
                $room_item['paipai_info']['status'] = $info['status'];
                $room_item['paipai_info']['score_12'] = $info['score_12'];
                $room_item['paipai_info']['score_34'] = $info['score_34'];
                $room_item['paipai_info']['score_56'] = $info['score_56'];
                $room_item['paipai_info']['end_time'] = strtotime($info['created_at']) + $info['second_num'];
            }
        }

        return $room_item;
    }

    /**
     * callback进入房间
     * @param $room_id
     * @param $user_id
     * @return bool
     * */
    public function callback_user_add($room_id, $user_id)
    {
        //超管不在房间列表
        if ($this->model_user->is_super($user_id)) {
            return false;
        }
        $add_ret = $this->model_room_user->add_user($room_id, $user_id);

        //记录房间缓存
        $this->model_room->IncrRoomOpenListCache($room_id, 'roomUserNum', 1);

        return $add_ret;
    }

    /**
     * 离开房间
     * @param $room_id
     * @return mixed|null
     */
    public function del($room_id)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return null;
        }
        $ret = $this->model_room_user->del_user($room_id, $current_user['user_id']);
        /*
        $room_user_count = $this->model_room_user->get_users_count($room_id);
        if (empty($room_user_count)){
            $lib_rc = new rc();
            $lib_rc->chat_room_unkeepalive($room_id);
        }*/
        return $ret;
    }

    /**
     * callback 退出房间
     * @param $room_id
     * @param $user_id
     * @return bool
     * */
    public function callback_del($room_id, $user_id)
    {
        $ifexist = $this->model_room_user->exists($room_id, $user_id);
        $ret = $this->model_room_user->del_user($room_id, $user_id);
        //记录房间缓存
        if ($ifexist) {
            $this->model_room->IncrRoomOpenListCache($room_id, 'roomUserNum', -1);
        }

        return $ret;
    }

    /**
     * 房间内用户列表
     * @param $room_id
     * @param int $guardId 此参数暂时无用
     * @return mixed
     */
    public function get_users($room_id, $guardId = -1)
    {
        $id_arr = $this->model_room_user->get_usersids($room_id);
        if ($id_arr == null) {
            return [];
        }

        $wallets = $this->model_userwallet->get_wallets($id_arr);
        $attires = $this->model_mall->get_goods_attire_ids($id_arr);
        $dic_wallet = [];
        for ($i = 0; $i < count($wallets); $i++) {
            $dic_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $data = $this->model_user->get_users_by_ids($id_arr);
        $medalArr = $this->modelMedal->getMedalUserListCache($id_arr, false);
        $medalData = [];
        foreach ($medalArr as $val) {
            if (empty($val)) {
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }

        //获取用户的公会id
        $unionUsers = collect($this->modelUnionUser->getUnionByUser($id_arr))->keyBy('user_id')->toArray();
        for ($i = 0; $i < count($data); $i++) {
            $data[$i]['diamond_balance'] = intval($dic_wallet[$data[$i]['user_id']]['diamond_balance']);
            $data[$i]['charm_balance'] = intval($dic_wallet[$data[$i]['user_id']]['charm_balance']);
            $data[$i]['wealth_balance'] = intval($dic_wallet[$data[$i]['user_id']]['wealth_balance']);
            $data[$i]['celebrity_balance'] = intval($dic_wallet[$data[$i]['user_id']]['celebrity_balance']);
            $data[$i]['reputation_balance'] = intval($dic_wallet[$data[$i]['user_id']]['reputation_balance']);
            if (array_key_exists(intval($data[$i]['user_id']), $attires)) {
                $data[$i]['attires'] = $attires[intval($data[$i]['user_id'])];
            } else {
                $data[$i]['attires'] = [];
            }

            if (array_key_exists(intval($data[$i]['user_id']), $medalData)) {
                $data[$i]['medal'] = $medalData[intval($data[$i]['user_id'])];
            } else {
                $data[$i]['medal'] = [];
            }

            // 获取用户是否使用道具
            $propUseInfo = $this->userPropModel->getPropUseTime(intval($data[$i]['user_id']), 15);
            $data[$i]['user_prop']['hide_info'] = $propUseInfo ? true : false;
            $data[$i]['union_id'] = $unionUsers[$data[$i]['user_id']]['un_id'] ?? 0;//用户所属公会id
        }

        return $data;
    }

    /**
     * 获取所有麦位用户user_id
     *
     * Created at 2021/11/25 17:32
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $roomId
     * @return array
     */
    private function getAllMicroUserIds(int $roomId): array
    {
        $hostMicroUserId = $this->modelRoomHostMicro->get_user_id($roomId);//主持麦用户id
        $roomInfo = $this->model_room->get_room($roomId);
        $commonMicroUserIds = (new AnnualCeremonyServices())->getRoomMicros($roomId, $roomInfo['room_type']['id']);//普通麦位用户ids
        return array_merge($hostMicroUserId ? [$hostMicroUserId] : [], $commonMicroUserIds);//合并
    }

    /**
     * 房间内用户列表(带分页)
     *
     * @param int $room_id
     * @param int $guardId 此参数暂时无用
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function get_users_v2(int $roomId, int $guardId = -1, int $page = 0, int $pageSize = 20): array
    {
        $pageSize = 1000;
        $result = ['micro_user_list' => [], 'online_user_list' => [], 'online_user_num' => 0];
        $id_arr = $this->model_room_user->get_usersids($roomId);
        if ($id_arr == null) {
            return $result;
        }
        $result['online_user_num'] = count($id_arr);

        $microUserIds = $this->getAllMicroUserIds($roomId);//麦位user_ids
        //分页读取用户user_id
        $start = $page * $pageSize;
        $onlineUserIds = array_diff(array_slice($id_arr, $start, $pageSize), $microUserIds);//过滤掉麦位上的用户user_id
        $allUserIds = array_merge($microUserIds, $onlineUserIds);
        $wallets = $this->model_userwallet->get_wallets($allUserIds);
        $attires = $this->model_mall->get_goods_attire_ids($allUserIds);
        $dic_wallet = collect($wallets)->keyBy('user_id')->toArray();

        $data = $this->model_user->get_users_by_ids($allUserIds);
        $medalArr = $this->modelMedal->getMedalUserListCache($allUserIds, false);
        $medalData = [];
        foreach ($medalArr as $val) {
            if (empty($val)) {
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }

        //获取用户的公会id
        $unionUsers = collect($this->modelUnionUser->getUnionByUser($allUserIds))->keyBy('user_id')->toArray();
        for ($i = 0; $i < count($data); $i++) {
            $key = intval($data[$i]['user_id']);
            $data[$i]['diamond_balance'] = intval($dic_wallet[$key]['diamond_balance']);
            $data[$i]['charm_balance'] = intval($dic_wallet[$key]['charm_balance']);
            $data[$i]['wealth_balance'] = intval($dic_wallet[$key]['wealth_balance']);
            $data[$i]['celebrity_balance'] = intval($dic_wallet[$key]['celebrity_balance']);
            $data[$i]['reputation_balance'] = intval($dic_wallet[$key]['reputation_balance']);
            $data[$i]['jd_balance'] = intval($dic_wallet[$key]['jd_balance']);
//            $data[$i]['game_balance'] = intval($dic_wallet[$key]['game_balance']);
            $data[$i]['game_balance'] = empty(intval($dic_wallet[$key]['game_balance'])) ? 1 : intval($dic_wallet[$key]['game_balance']);
            $data[$i]['agent_jd_balance'] = intval($dic_wallet[$key]['agent_jd_balance']);
            $data[$i]['debris_balance'] = intval($dic_wallet[$key]['debris_balance']);
            $data[$i]['attires'] = array_key_exists($key, $attires) ? $attires[$key] : [];
            $data[$i]['medal'] = array_key_exists($key, $medalData) ? $medalData[$key] : [];

            // 获取用户是否使用道具
            $propUseInfo = $this->userPropModel->getPropUseTime($key, 15);
            $data[$i]['user_prop']['hide_info'] = $propUseInfo ? true : false;
            $data[$i]['union_id'] = $unionUsers[$key]['un_id'] ?? 0;//用户所属公会id

            //用户铭牌
            $data[$i]['userNameplate'] = $this->nameplateService->getNameplateByUserId($data[$i]['user_id']);
        }
        $userGuardInfo = $this->getUserGuardInfo($roomId, array_column($data, 'user_id'));//守护信息
        $dataFormat = collect($data)->keyBy('user_id')->toArray();
        foreach ($microUserIds as $microUserId) {
            if (isset($dataFormat[$microUserId])) {
                $dataFormat[$microUserId]['guard_attribute'] = $userGuardInfo[$microUserId] ?? [];
                $result['micro_user_list'][] = $dataFormat[$microUserId];
            }
        }

        foreach ($onlineUserIds as $onlineUserId) {
            if (isset($dataFormat[$onlineUserId])) {
                $dataFormat[$onlineUserId]['guard_attribute'] = $userGuardInfo[$onlineUserId] ?? [];
                $result['online_user_list'][] = $dataFormat[$onlineUserId];
            }
        }
        return $result;
    }

    /**
     * 获取房间主持麦的守护用户信息
     *
     * Created at 2021/12/7 11:16
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $roomId
     * @param array $userIds
     * @return array
     */
    public function getUserGuardInfo(int $roomId, array $userIds): array
    {
        $hostMicroUserId = $this->modelRoomHostMicro->get_user_id($roomId);//主持麦用户id
        if (!$hostMicroUserId) {
            return [];
        }


        $where[] = [
            function ($query) use ($userIds) {
                $query->whereIn('user_id', $userIds);
            },
        ];
        $where['guard_user_id'] = $hostMicroUserId;
        $where[] = ['expire_time', '>', time()];
        $guardInfo = $this->modelGuard->getGuardList($where);
        $guardMap = [];
        foreach ($guardInfo as $guard) {
            if (!isset($guardMap[$guard['user_id']])) {
                $guardMap[$guard['user_id']] = [];
            }

            $userId = $guard['user_id'];
            unset($guard['guard_id']);
            unset($guard['user_id']);
            unset($guard['guard_user_id']);
            unset($guard['guard_type_id']);
            $guardMap[$userId][] = $guard;
        }

        return $guardMap;
    }

    /**
     * 获取当前用户所在房间
     * @param $user_id
     * @return int|null
     */
    public function get_cur_room($user_id)
    {
        $room_id = $this->model_room_user->get_user_cur_room($user_id);
        if (empty($room_id)) {
            return null;
        }

        //获取用户是否使用防跟随道具
        $propUseInfo = $this->userPropModel->getPropUseTime($user_id, 19);
        if ($propUseInfo) {
            return null;
        }

        $data = $this->model_room->get_room($room_id);
        return $data;
    }


    public function getCurRoomId($user_id)
    {
        $room_id = $this->model_room_user->get_user_cur_room($user_id);
        return $room_id;
    }


    /**
     * 当前用户是否在房间内
     * @param $room_id
     * @return bool
     */
    public function user_exist($room_id)
    {
        if (empty($room_id)) {
            return false;
        }
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)) {
            return false;
        }
        $tmp_room_id = $this->model_room_user->get_user_cur_room($cur_user['user_id']);
        if (empty($tmp_room_id)) {
            return false;
        }
        if ($tmp_room_id != $room_id) {
            return false;
        }
        return true;
    }


    /*
       * 设置可访问房间类型
       * @param [$phone]   注册电话
       * @param [$typeArr]   注册电话
       * */
    public function set_room_allow_type($type, $typeStr)
    {
        return $this->model_room_user->setJoinAllowType($type, $typeStr);
    }

    /*
     *查看已经设置类型
     * */
    public function show_room_allow_type($typeArr)
    {
        return $this->model_room_user->getJoinAllowType($typeArr);
    }

    /**
     * 处理房间审核数据
     * @param $roomId
     * @param $data 房间数据
     * @return array
     */
    public function roomContentCheckHandle($roomId, $data)
    {
        //查询审核相关数据是否存在
        $contentCheckList = $this->contentCheckModel->getContentCheckListByDataIdAndCheckObj($roomId, [3, 4, 5, 7]);
        foreach ($contentCheckList as $key => $value) {
            if ($value['check_obj'] == 3) {
                $data['name'] = $value['content'];
            }

            if ($value['check_obj'] == 4) {
                $data['notice'] = $value['content'];
            }

            if ($value['check_obj'] == 5) {
                $data['desc'] = $value['content'];
            }

//            if ($value['check_obj'] == 7) {
//                $data['image'] = $value['content'];
//            }
        }

        return $data;
    }

    public function getRoleById($roomId, $userId)
    {
        $role = $this->model_room->get_role($roomId, $userId);
        return $role;
    }
}